from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
from pydantic import BaseModel
from typing import Optional
from app.core.database import get_db
from app.models.visit_log import VisitLog

router = APIRouter()

class VisitLogRequest(BaseModel):
    wechat_openid: Optional[str] = None
    page: Optional[str] = None
    action: Optional[str] = None

@router.post("/log")
def log_visit(
    visit_data: VisitLogRequest,
    request: Request,
    db: Session = Depends(get_db)
):
    ip_address = request.client.host if request.client else None
    
    visit_log = VisitLog(
        wechat_openid=visit_data.wechat_openid,
        page=visit_data.page,
        action=visit_data.action,
        ip_address=ip_address
    )
    db.add(visit_log)
    db.commit()
    
    return {"message": "访问日志已记录"}

